package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FtpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service("iFileService")
public class FileServiceimpl implements IFileService {

    private Logger logger = LoggerFactory.getLogger(FileServiceimpl.class);

    public String upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        String uploadFileName = UUID.randomUUID().toString()+'.'+fileExtensionName;
        logger.info("开始上传文件，上传文件的文件名:{},上传的路径:{},新文件名:{}",fileName,path,uploadFileName);

        File fileDir = new File(path);
        if (!fileDir.exists()){
            // 可写权限
            fileDir.setWritable(true);
            // 创建目录
            fileDir.mkdirs();
        }
        File files = new File(path,uploadFileName);

        try {
            file.transferTo(files);
            // 文件已经上传成功
            //todo files 上传到ftp服务器上
            FtpUtil.uploadFile(Lists.newArrayList(files));
            // 已经上传
            //todo 上传完后将删除当前到upload下面到文件
            files.delete();
        } catch (IOException e) {
            logger.error("上传文件异常",e);
            return null;
        }
        return files.getName();
    }
}
